<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>02.let练习</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .container {
      width: 100%;
      height: 300px;
      border: 1px solid #ccc;
    }

    .container>.item {
      width: 30%;
      height: 200px;
      border: 1px solid red;
      margin: 50px 20px;
      float: left;
    }
  </style>
</head>

<body>
  <h1>切换背景颜色</h1>
  <div class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
  <script>
    /* 
     *var 之前改变背景颜色
     */
    /*  var items = document.querySelectorAll(".item");
     for (var i = 0; i < items.length; i++) {
         items[i].onclick = function() {
             console.log(i); //i为3，所以无法设置背景颜色
             //items[i].style.backgroundColor = "red";
             this.style.backgroundColor = "red";
         }
     } */


    //2.let 写法改变背景颜色
    let items = document.querySelectorAll(".item");
    for (let i = 0; i < items.length; i++) {
      items[i].onclick = function () {
        items[i].style.backgroundColor = "blue";
      }
    }
  </script>
</body>

</html>